<template>
  <div class="kcjpz">
    <div class="tool">
      <ToolBar
          :show-all="false"
          :add-data="setDialogVisible"
          :update-data="updateDialogVisible"
          :delete-data="deleteById"
          :delete-disable="multipleSelection.length<=0"
          :update-disable="multipleSelection.length!==1"
          :show-multiple="false"
      ></ToolBar>
    </div>
    <el-table
        :data="tableData"
        stripe
        border
        @selection-change="handleSelectionChange"
        default-expand-all
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}">
      <el-table-column type="selection" width="50" label="序号">
      </el-table-column>
      <el-table-column label="扣除类型" prop="ntype">
        <template slot-scope="scope">
          {{ scope.row.ntype === 0 ? '考勤组别' : '部门班别' }}
        </template>
      </el-table-column>
      <el-table-column label="考勤组别/部门班别" prop="cgroupName">
      </el-table-column>
      <el-table-column label="扣除时长(分钟)" prop="ndeductionTime">
      </el-table-column>
      <el-table-column label="生效时间">
        <template slot-scope="scope">
          {{ scope.row.deffectiveDate|formatDate }}
        </template>
      </el-table-column>

      <el-table-column label="失效时间" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.dexpiringDate|formatDateYX }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.createTime|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.updateTime|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="120">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          hide-on-single-page
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size=size
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
    <el-dialog :title="'扣除时间段参数'+(isAdd?'添加':'修改')" :visible.sync="dialogFormVisible"
               :before-close="handleClose" size="35%">
      <el-form :model="form" label-position="left" :rules="rules" ref="form">
        <el-form-item label="扣除类型" :label-width="formLabelWidth" prop="ntype">
          <el-select v-model="form.ntype" style="width:100%" :disabled="!isAdd">
            <el-option :value="0" label="考勤组别">
            </el-option>
            <el-option :value="1" label="部门班别">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考勤组别" :label-width="formLabelWidth"  v-if="!parseInt(form.ntype)">
          <!--        <el-input v-model="form.cgroupId" autocomplete="off" :disabled="!isAdd"></el-input>-->
          <el-select v-model="group" class="w100" value-key="id" @change="groupChange" :disabled="!isAdd"
                     :multiple="true">
            <el-option v-for="item in groupList" :label="item.groupName" :value="item" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门班别" :label-width="formLabelWidth" v-else>
          <el-select v-model="dept" class="w100" value-key="deptLevel2" @change="deptChange" :disabled="!isAdd"
                     :multiple="true">
            <el-option v-for="item in deptList" :label="item.deptLevel2" :value="item" :key="item.deptLevel2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="扣除时长" :label-width="formLabelWidth" prop="ndeductionTime">
          <el-input v-model="form.ndeductionTime" autocomplete="off" :disabled="!isAdd" type="number" :min="0">
            <template slot="append">分钟</template>

          </el-input>
        </el-form-item>
        <el-form-item label="生效时间" :label-width="formLabelWidth" prop="deffectiveDate">
          <el-date-picker type="datetime" v-model="form.deffectiveDate" class="w100"
                          :disabled="!isAdd"></el-date-picker>
        </el-form-item>
        <el-form-item label="失效时间" :label-width="formLabelWidth" prop="dexpiringDate">
          <el-date-picker type="datetime" v-model="form.dexpiringDate" class="w100"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="isAdd?addData('form'):updateById('form')">确 定 <span
            v-text="isAdd?'添 加':'修 改'"></span></el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import ToolBar from "@/components/common/ToolBar.vue";

export default {
  components: {ToolBar},
  name: "Kcsjpz",
  data() {
    return {
      title: "",
      currentPage: 1,
      total: 0,
      size: 10,
      tableData: [],
      multipleSelection: [],
      form: {
        ntype: null,
        cgroupId: null,
        cgroupName: null,
        deffectiveDate: null,
        ndeductionTime: 30,
        dexpiringDate: null
      },
      dialogFormVisible: false,
      formLabelWidth: "85px",
      rules: {
        nType: [
          {
            required: true, message: "请选择扣除类型...", trigger: "change"
          }
        ],
        groupName: [{
          required: true, message: "请选择部门班别/考勤组...", trigger: "change"
        }],
        ndeductionTime: [{
          required: true, message: "请输入扣除时长...", trigger: "blur"
        }],
        deffectiveDate: [
          {
            required: true, message: "请选择生效时间...", trigger: "change"
          }
        ]
        //   paramValue: [{
        //     required: true, message: "请输入参数值...", trigger: "blur"
        //   }],
      },
      isAdd: true,
      group: [],
      groupList: [],
      dept: [],
      deptList: []
    }
  },
  created() {
  },
  mounted() {
    this.getDataList()

    this.getGroupList()

    this.getDeptList()
  },
  methods: {
    handleClose(done) {
      console.log("Donw:", done)
      this.$confirm('确认关闭？')
          .then(_ => {
            this.form = {}
            this.dialogFormVisible = false
            done();
          })
          .catch(_ => {
          });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleEdit(index, row) {
      console.log("参数：", row);
      this.form = this.$tools.deepClone(row)
      console.log("ForM:",this.form)
      if(!parseInt(this.form.ntype)){
        this.group=[]
        console.log("G")
        this.group.push({id: this.form.cgroupId, groupName: this.form.cgroupName, groupId: this.form.cgroupId})
      }else{
        this.dept=[]
        console.log("D")

        this.dept.push({id: 1, deptLevel2: this.form.cgroupName})

      }
      this.setDialogVisible(false)
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$tools.showMessageBox("确认删除" + row.cgroupName + "(" + row.ndeductionTime + ")？", "操作确认", 'warning').then(confirm => {
        axios.delete("/kcsjdpz/remove?id=" + row.id).then(res => {
          if (res.data.success) {
            this.$tools.showMessage("参数" + row.cgroupName + "(" + row.ndeductionTime + ")删除成功！", "success")
            this.getDataList()
          }
        })

      }).catch(cancel => {
        this.$tools.showMessage("操作已取消！", "info")

      })
    },
    getDataList() {
      this.dialogFormVisible = false
      console.log("查询数据：", this.form)
      console.log("T:", this.currentPage)
      axios.get("/kcsjdpz/selectBatchByPage?pageNum=" + this.currentPage + "&pageSize=" + this.size, this.form).then(res => {
        console.log("打卡信息：", res)
        if (res.data.success) {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          this.pages = res.data.data.pages
        } else {
          this.tableData = []
          this.total = 0
          this.pages = 1

        }
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getDataList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getDataList()
    },
    setDialogVisible(isAdd) {
      this.dialogFormVisible = true
      if(isAdd){
        this.form={}
        this.dept=[]
        this.group=[]
      }

      this.isAdd = isAdd
    },
    deleteById() {
      this.$tools.showMessageBox("确认删除" + this.multipleSelection.length + "条记录？", "批量删除确认", "warning").then(confirm => {
        axios.post("/kcsjdpz/deleteBatch", this.multipleSelection).then(res => {
          console.log("批量删除结果：", res)
          if (res.data.success) {
            this.$tools.showMessage("删除成功！", "success")
            this.getDataList()
          } else {
            this.$tools.showMessage("删除失败！", "danger")
          }
        })
      }).catch(cancel => {
        this.$tools.showMessage("操作已取消！", "info")
      })
    },
    updateDialogVisible() {
      this.form = this.$tools.deepClone(this.multipleSelection[0])
      console.log("FDS:",this.form)
      if(!parseInt(this.form.ntype)){
        this.group=[]
        this.group.push({id: this.form.cgroupId, groupName: this.form.cgroupName, groupId: this.form.cgroupId})

      }else{
        this.dept=[]
        this.dept.push({id: 1, deptLevel2: this.form.cgroupName})

      }

      this.setDialogVisible(false)
    },
    updateById(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.form.updateUserId = this.$store.state.userInfo.id
          axios.put("/kcsjdpz/update", this.form).then(res => {
            if (res.data.success) {
              this.$tools.showMessage("修改成功", "success")
              this.dialogFormVisible = false
              this.getDataList()
              this.form = {}
            } else {
              this.$tools.showMessage("修改失败", "danger")

            }
          })
        } else {
          this.$tools.showMessage("请检查您输入的信息...", "warning")
        }
      })
    },
    addData(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.form.createUserId = this.$store.state.userInfo.id
          let dataList = []
          if(this.form.ntype){
            if (this.dept.length===0) {
              this.$tools.showMessage("请选择部门班别...", "warning")
              return;
            }else{
              this.dept.forEach(item => {
                let data = this.$tools.deepClone(this.form)
                data.cgroupName = item.deptLevel2
                dataList.push(data)
              })
            }

          }else{
            if (this.group.length===0) {
              this.$tools.showMessage("请选择考勤组别...", "warning")
              return;
            }else{
              this.group.forEach(item => {
                let data = this.$tools.deepClone(this.form)
                data.cgroupId = item.groupId
                data.cgroupName = item.groupName
                dataList.push(data)
              })
            }

          }



          axios.post("/kcsjdpz/saveBatch", dataList).then(res => {
            if (res.data.success) {
              this.$tools.showMessage("添加成功", "success")
              this.dialogFormVisible = false
              this.getDataList()
            } else {
              this.$tools.showMessage("添加失败", "error")

            }
          })

        } else {
          this.$tools.showMessage("请检查您输入的信息...", "warning")
        }
      })
    },
    getGroupList() {
      axios.get("/ding_attendance_group/list").then(res => {

        if (res.data.success) {
          this.groupList = res.data.data
        } else {
          this.groupList = []
        }
      })
    },
    getDeptList(){
      axios.get("/kcsjdpz/getDeptList").then(res => {
        if (res.data.success) {
          this.deptList = res.data.data
        } else {
          this.deptList = []
        }
      })
    },
    groupChange() {
      console.log("Group:", this.group)
      this.form.cgroupId = this.group.groupId
      this.form.cgroupName = this.group.groupName
    },
    deptChange(){
      console.log("dept:", this.dept)
      this.form.cgroupId = null
      this.form.cgroupName = this.dept.deptLevel2
    }

  }
}
</script>
<style scoped>

</style>
